<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="toggle">添加/修改</button>
    </div>
    <div>
      <table border="1" cellPadding="10" cellSpacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, i) in arr" :key="i">
          <td>{{ i + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ !item.gender ? "女" : "男" }}</td>
          <td>
            <button @click="del(i)">删除</button>
            <button @click="edit(i)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      index: 0, //全局index用来判断点击编辑之后是那个数据到输入框编辑
      flag: true,
      name: "",
      age: "",
      gender: "男",
      arr: [
        {
          name: "Tom",
          age: 19,
          gender: 1,
        },
        {
          name: "Jone",
          age: 21,
          gender: 0,
        },
        {
          name: "小李",
          age: 18,
          gender: 1,
        },
      ],
    };
  },
  methods: {
    //切换
    toggle() {
      if (!this.name || !this.age) return alert("姓名和名字不能为空");
      if (this.flag) {
        let x = this.gender === "男" ? 1 : 0;
        this.arr.push({
          name: this.name,
          age: this.age,
          gender: x,
        });
        this.name = "";
        this.age = "";
        this.gender = "";
      } else {
        this.flag = true;
        this.arr[this.index].name = this.name;
        this.arr[this.index].age = this.age;
        this.arr[this.index].gender = this.gender === "男" ? 1 : 0;
        this.name = "";
        this.age = "";
        this.gender = "";
      }
    },
    //编辑
    edit(i) {
      this.index = i;
      this.flag = false;
      let x = this.arr[i].gender ? "男" : "女";
      this.name = this.arr[i].name;
      this.age = this.arr[i].age;
      this.gender = x;
    },
    //删除
    del(i) {
      this.arr.splice(i, 1);
    },
  },
};
</script>
